/**
 * 
 */
package com.miolr.core.struts2;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.convention.ConventionUnknownHandler;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.config.entities.ResultTypeConfig;
import com.opensymphony.xwork2.config.providers.InterceptorBuilder;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;

/**
 * @author iday
 * 
 */
public class RestfulUnkownHandler extends ConventionUnknownHandler {

    @Inject
	public RestfulUnkownHandler(Configuration configuration, ObjectFactory objectFactory,
            ServletContext servletContext, Container container,
            @Inject("struts.convention.default.parent.package") String defaultParentPackageName,
            @Inject("struts.convention.redirect.to.slash") String redirectToSlash,
            @Inject("struts.convention.action.name.separator") String nameSeparator) {
		super(configuration, objectFactory, servletContext, container,
				defaultParentPackageName, redirectToSlash, nameSeparator);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.struts2.convention.ConventionUnknownHandler#buildActionConfig
	 * (java.lang.String,
	 * com.opensymphony.xwork2.config.entities.ResultTypeConfig)
	 */
	@Override
	protected ActionConfig buildActionConfig(String path,
			ResultTypeConfig resultTypeConfig) {
		Map<String, ResultConfig> results = new HashMap<String, ResultConfig>();
		HashMap<String, String> params = new HashMap<String, String>();
		if (resultTypeConfig.getParams() != null) {
			params.putAll(resultTypeConfig.getParams());
		}
		params.put(resultTypeConfig.getDefaultResultParam(), path);

		PackageConfig pkg = configuration
				.getPackageConfig(defaultParentPackageName);
		List<InterceptorMapping> interceptors = InterceptorBuilder
				.constructInterceptorReference(pkg,
						pkg.getFullDefaultInterceptorRef(),
						Collections.<String, String> emptyMap(), null,
						objectFactory);
		ResultConfig config = new ResultConfig.Builder(Action.SUCCESS,
				resultTypeConfig.getClassName()).addParams(params).build();
		results.put(Action.SUCCESS, config);

		return new ActionConfig.Builder(defaultParentPackageName, "execute",
				pkg.getDefaultClassRef()).addInterceptors(interceptors)
				.addExceptionMappings(pkg.getAllExceptionMappingConfigs())
				.addResultConfigs(results).build();
	}

}
